
import ResSetting from "./ResSetting";


export class ResCache {
    private _path: string;
    public get path(): string {
        return this._path;
    }

    protected ref: number = 0;
    protected tick: number = 0;
    protected autoDestroy: boolean = true;
    protected isLoading: boolean = false;
    private handles: Array<any> = [];

    public get refCount(): number {
        return this.ref;
    }

    public constructor(path: string) {
        this._path = path;
        this.tick = Date.now();
    }

    /**
     * 开始加载资源
     * @returns 
     */
    public load(callback: Function, target: any) {
        if (this.isValid()) {
            this.handleCallback(callback, target);
            return;
        }
        this.handles.push({ callback, target });
        this.loadRes();
    }

    /**
     * 开始加载资源
     * @returns 
     */
    protected loadRes() {
        if (this.isLoading || this.isValid()) return;
        this.isLoading = true;
        this.onLoadRes();
    }

    /**
     * 开始加载资源
     * @returns 
     */
    protected onLoadRes() {

    }

    /**
     * 加载资源完成
     * @returns 
     */
    protected loadFinish(asset: any) {
        this.isLoading = false;
        let handles = this.handles;
        for (let i = 0; i < handles.length; ++i) {
            var callback = handles[i].callback;
            var target = handles[i].target;
            this.handleCallback(callback, target);
        }
        handles.splice(0, handles.length);
    }

    /**
     * 处理回调
     * @param callback 
     * @param target 
     */
    protected handleCallback(callback: Function, target: any) {
        callback.call(target, this);
    }

    /**
     * 检测资源是否需要销毁
     * @param now 
     * @returns 
     */
    public check(now: number): boolean {
        return this.autoDestroy && this.refCount <= 0 && (now - this.tick > ResSetting.MaxFreeTime);
    }

    /**
     * 派生对象
     * @param name 
     * @returns 
     */
    public spawn(name?: string): any {
        return null;
    }

    /**
     * 派生对象
     * @param name 
     * @returns 
     */
    public unSpawn(obj?: any) {

    }

    /**
     * 派生对象
     * @param name 
     * @returns 
     */
    public unSpawnAll(name: string) {

    }

    public setAutoDestroy(enable: boolean) {
        this.autoDestroy = enable;
    }

    /**
     * 释放资源
     */
    public release() {

    }

    /**
     * 资源是否有效
     */
    protected isValid(): boolean {
        return true;
    }
}